package com.erp.hrms.controller;

import com.erp.hrms.common.BaseResp;
import com.erp.hrms.enums.CommonEnum;
import com.erp.hrms.service.AdminService;
import com.erp.hrms.vo.AdminVo;
import com.erp.hrms.vo.ParamVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import static com.erp.hrms.enums.Atom.LOGIN_TOKEN;

@RestController
@RequestMapping("/admin")
@Slf4j
public class AdminController {

    @Resource
    private AdminService adminService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @PostMapping("/login")
    public BaseResp login(@RequestBody ParamVo paramVo, HttpServletRequest request, HttpServletResponse response) {
        BaseResp baseResp;
        try {
            paramVo.setRequest(request);
            paramVo.setResponse(response);
            baseResp = adminService.login(paramVo);
        } catch (Exception e) {
            log.error(e.toString());
            baseResp = new BaseResp(CommonEnum.FAIL);
        }
        return baseResp;
    }

    @PostMapping("/modifyPwd")
    public BaseResp modifyPwd(@RequestBody ParamVo paramVo, HttpServletRequest request) {
        BaseResp baseResp;
        try {
            paramVo.setRequest(request);
            baseResp = adminService.modifyPwd(paramVo);
        } catch (Exception e) {
            log.error(e.toString());
            baseResp = new BaseResp(CommonEnum.FAIL);
        }
        return baseResp;
    }

    @PostMapping("/signOut")
    public BaseResp signOut(@RequestBody ParamVo paramVo, HttpServletRequest request) {
        HttpSession session = request.getSession();
        session.invalidate();
        stringRedisTemplate.delete(LOGIN_TOKEN + paramVo.getId());
        return new BaseResp(CommonEnum.ADMIN_SIGN_OUT);
    }

    @PostMapping("/insertAdmin")
    public BaseResp insertAdmin(@RequestBody AdminVo adminVo) {
        BaseResp baseResp;
        try {
            baseResp = adminService.insertAdmin(adminVo);
        } catch (Exception e) {
            log.error(e.toString());
            baseResp = new BaseResp(CommonEnum.FAIL);
        }
        return baseResp;
    }

    @PostMapping("/modifyAdmin")
    public BaseResp modifyAdmin(@RequestBody AdminVo adminVo) {
        BaseResp baseResp;
        try {
            baseResp = adminService.modifyAdmin(adminVo);
        } catch (Exception e) {
            log.error(e.toString());
            baseResp = new BaseResp(CommonEnum.FAIL);
        }
        return baseResp;
    }
}
